package com.bjc.platform.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bjc.platform.Constants;
import com.bjc.platform.model.AdmOrg;
import com.bjc.platform.model.AdmRole;
import com.bjc.platform.model.AdmUser;
import com.bjc.platform.model.CustomUserDetails;
import com.bjc.platform.service.AdmUserService;
import com.bjc.platform.util.ExcelColumnDefinition;
import com.bjc.platform.util.ExcelExporter;
import com.bjc.platform.util.JSONHelper;
import com.bjc.platform.util.Page;
import com.bjc.platform.util.StaticMethod;
import com.bjc.platform.vo.AdmUserSearchCondition;
import com.bjc.platform.vo.LoginVo;

@Controller
@RequestMapping("/user")
public class AdmUserController extends BaseController {
	// 用户初始密码
	private static final String INIT_PASSWORD = "123456";
	@Autowired
	@Qualifier("userService")
	private AdmUserService userService;
	
//	@Autowired
//	@Qualifier("hrManagerService")
//	private IHRManagerService hrManagerService;

	@RequestMapping(value = "/query", method = RequestMethod.GET)
	@ResponseBody
	public Object query(@RequestParam("page") int page,
			@RequestParam("start") int start, @RequestParam("limit") int limit,
			@RequestParam HashMap<String, Object> reqParam) throws Exception {

		AdmUserSearchCondition cond = (AdmUserSearchCondition) JSONHelper
				.json2Object(String.valueOf(reqParam.get("condition")),
						AdmUserSearchCondition.class);
		PageRequest pr = new PageRequest(page - 1, limit);
		Page userPage = userService.search(cond, pr);

		return StaticMethod.TOListJSONResult(true, userPage.getResult(),
				userPage.getTotalCount()).getJSONResult();
	}

	/**
	 * 根据用户名称查询用户, 不支持分页， 用于Combo组件
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/queryByName", method = RequestMethod.GET)
	@ResponseBody
	public Object queryByName(@RequestParam("username") String username) {

		AdmUserSearchCondition cond = new AdmUserSearchCondition();
		cond.setUsername(username);
		Page userPage = userService.search(cond, null);
		boolean success = false;
		if (userPage != null && userPage.getResult() != null
				&& userPage.getResult().size() == 0) {
			success = true;
		}

		return StaticMethod.TOListJSONResult(success, userPage.getResult(),
				null).getJSONResult();
	}

	/**
	 * 根据用户名称查询用户, 不支持分页， 用于Combo组件
	 * 
	 * @param username
	 * @return
	 */
	@RequestMapping(value = "/getUserCombo", method = RequestMethod.POST)
	@ResponseBody
	public Object getUserCombo(@RequestParam("username") String username) {

		AdmUserSearchCondition cond = new AdmUserSearchCondition();
		cond.setUsername(username);
		Page userPage = userService.search(cond, null);
		return StaticMethod.TOListJSONResult(true, userPage.getResult(), null)
				.getJSONResult();
	}

	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	public Object save(@RequestParam HashMap<String, Object> reqParam) throws Exception {
		CustomUserDetails loginUser = StaticMethod.getUser();
		AdmUser user = (AdmUser) JSONHelper.json2Object(
				JSONHelper.map2json(reqParam), AdmUser.class);
		
		int valid = userService.validUserCheck(user);
		if (AdmUserService.VALID_USER == valid) {

			AdmUser persist = null;

			AdmOrg org = new AdmOrg();
			Long orgId = StaticMethod.object2Long(reqParam.get("orgId"));

			Object oRoleIds = reqParam.get("roleIds");
			Object oEmployeeId = reqParam.get("employeeId");
			//Employee employee = null;

			org.setId(orgId);
//			if (oEmployeeId != null
//					&& !StringUtils.isEmpty(String.valueOf(oEmployeeId))) {
//				employee = user.getEmployee();
//				if (employee == null) {
//					try{
//						employee = hrManagerService.queryOne(Integer.valueOf(String.valueOf(oEmployeeId)));
//						if(employee == null){
//							validEmployee = true;
//						}
//					}catch(Exception e){
//						validEmployee = true;
//					}
//					
//					if(validEmployee){
//						return StaticMethod.TOJSONResult(false, "VALID_EMPLOYEE")
//								.getJSONResult();
//					}
//				}
//			}

			Set<AdmRole> roles = new HashSet<AdmRole>();
			AdmRole role = null;
			if (oRoleIds != null) {
				String[] roleIds = String.valueOf(oRoleIds).split(",");
				for (String id : roleIds) {
					if (!StringUtils.isEmpty(id)) {
						role = new AdmRole();
						role.setId(Long.valueOf(id));
						roles.add(role);
					}
				}
			}

			Md5PasswordEncoder md5 = new Md5PasswordEncoder();
			if (user != null && user.getId() != null) {
				persist = userService.get(user.getId());
				//persist.setEmployee(employee);
				persist.setOrgnize(org);
				persist.setRoles(roles);
				persist.setFullName(user.getFullName());
				persist.setSex(user.getSex());
				persist.setBirthday(user.getBirthday());
				persist.setEmail(user.getEmail());
				persist.setAddress(user.getAddress());
				persist.setMobilePhone(user.getMobilePhone());
				persist.setFlag(true);
				userService.save(persist);
			} else {
				user.setCreator(Long.valueOf(loginUser.getId()));
				user.setCreateTime(new Date());
				user.setOrgnize(org);
				user.setRoles(roles);
				//user.setEmployee(employee);
				user.setFlag(true);
				user.setPassword(md5.encodePassword(INIT_PASSWORD, null));
				userService.save(user);
			}
			return StaticMethod.TOJSONResult(true, null).getJSONResult();
		} else {
			if (AdmUserService.EXIST_USER_NAME == valid) {
				return StaticMethod.TOJSONResult(false, "EXIST_USER_NAME")
						.getJSONResult();
			}else{
				return StaticMethod.TOJSONResult(false, null).getJSONResult();
			}
		}
	}

	@RequestMapping(value = "/delete", method = RequestMethod.GET)
	@ResponseBody
	public Object delete(@RequestParam HashMap<String, Object> reqParam) {
		Long id = StaticMethod.object2Long(reqParam.get("id"));
		AdmUser user = userService.get(id);
		user.setFlag(false);
		// 标记删除
		userService.save(user);

		return StaticMethod.TOJSONResult(true, null).getJSONResult();
	}

	@RequestMapping(value = "/getLoginInfo", method = RequestMethod.GET)
	@ResponseBody
	public Object getLoginInfo(@RequestParam HashMap<String, Object> reqParam) {
		CustomUserDetails user = StaticMethod.getUser();
		LoginVo userVo = new LoginVo();
		AdmOrg org = user.getOrg() == null ? new AdmOrg() : user.getOrg();
		boolean success = false;
		if (user.getId() != null) {
//			userVo.setFullname(user.getFullName());
			userVo.setOrgDesc(user.getOrgDesc());
			userVo.setOrgId(user.getId());
			userVo.setUserId(user.getId());
			userVo.setUsername(user.getUsername());
			userVo.setOrgName(org.getName());
			userVo.setOrgCode(org.getCode());
			userVo.setDepartment(Constants.ORG_DEPARTMENT.equals(org.getOrgnizeType()));
			userVo.setGroup(Constants.ORG_GROUP.equals(org.getOrgnizeType()));
			success = true;
		}

		return StaticMethod.TOJSONResult(success, userVo).getJSONResult();
	}

	/**
	 * 根据查询条件导出用户信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/exportUser", method = RequestMethod.POST)
	public Object exportUser(HttpServletRequest request,
			HttpServletResponse response) {

		String username = StaticMethod.object2String(request
				.getParameter("username"));
		String fullname = StaticMethod.object2String(request
				.getParameter("fullname"));
		Long roleId = StaticMethod.object2Long(request.getParameter("roleId"));
		AdmUserSearchCondition cond = new AdmUserSearchCondition();
		if (!StringUtils.isEmpty(username)) {
			cond.setUsername(username);
		}
		if (!StringUtils.isEmpty(fullname)) {
			cond.setFullname(fullname);
		}
		if (roleId > 0) {
			cond.setRoleId(roleId);
		}
		Page userPage = userService.search(cond, null);

		List<ExcelColumnDefinition> coldfs = new ArrayList<ExcelColumnDefinition>();
		coldfs.add(new ExcelColumnDefinition("username", "用户名", (short) 2800));
		coldfs.add(new ExcelColumnDefinition("fullName", "姓名", (short) 3200));
		coldfs.add(new ExcelColumnDefinition("sexDesc", "性别", (short) 2000));
		coldfs.add(new ExcelColumnDefinition("birthday", "生日", (short) 3200));
		//coldfs.add(new ExcelColumnDefinition("email", "邮箱", (short) 7200));
		//coldfs.add(new ExcelColumnDefinition("mobilePhone", "电话", (short) 3200));
		//coldfs.add(new ExcelColumnDefinition("address", "地址", (short) 8800));
		coldfs.add(new ExcelColumnDefinition("orgDesc", "所属组织", (short) 10200));
		coldfs.add(new ExcelColumnDefinition("rolesDesc", "角色", (short) 6400));

		try {
			ExcelExporter.export("用户列表", coldfs, userPage.getResult(),
					response, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
	@ResponseBody
	public Object modifyPassword(@RequestParam("password") String pwd,
			@RequestParam("newPassword") String newPwd,
			@RequestParam("confirmPassword") String confirmNewPwd) {

		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		CustomUserDetails user = StaticMethod.getUser();
		AdmUser admUser = userService.get(user.getId());

		if (md5.encodePassword(pwd, null).equals(admUser.getPassword())) {
			admUser.setPassword(md5.encodePassword(newPwd, null));
			userService.save(admUser);
		} else {
			return StaticMethod.TOJSONResult(true, 1).getJSONResult(); // 旧密码不正确
		}

		return StaticMethod.TOJSONResult(true, 0).getJSONResult();
	}

	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
	@ResponseBody
	public Object resetPassword(@RequestParam("id") Long id) {
		Md5PasswordEncoder md5 = new Md5PasswordEncoder();
		AdmUser admUser = userService.get(id);
		admUser.setPassword(md5.encodePassword(INIT_PASSWORD, null));
		userService.save(admUser);
		return StaticMethod.TOJSONResult(true, 0).getJSONResult();
	}

}
